import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva/index';
import {
  Spin,
  Row,
  Empty,
  Col,
  Card,
  Form,
  Input,
  Select,
  Icon,
  Button,
  Dropdown,
  Menu,
  InputNumber,
  DatePicker,
  Modal,
  message,
  Badge,
  Divider,
  Steps,
  Radio,
  Table,
} from 'antd/lib/index';
import moment from 'moment/moment';
import router from 'umi/router';

import StandardTable from '@/components/StandardTable';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';

import styles from '../FundPosition/Test.less';

const FormItem = Form.Item;
const { Step } = Steps;
const { TextArea } = Input;
const { Option } = Select;
const RadioGroup = Radio.Group;
const getValue = obj =>
  Object.keys(obj)
    .map(key => obj[key])
    .join(',');

/* eslint react/no-multi-comp:0 */
@connect(({ fund, loading }) => ({
  fund,
  loading: loading.models.ruleTest,
}))
@Form.create()
class RCNexposure extends PureComponent {
  state = {
    filterData: [],
    expandForm: false, // 查询菜单栏 是否显示
    listLoading: false,
    formValues: {
      billType: 2,
      stock: '',
    }, // 查询菜单栏   查询参数
    modalVisible: false,
    updateModalVisible: false,

    selectedRows: [],

    stepFormValues: {},

    dataTradeList: {},
    updateParam: true,

    HistogramModalVisible: false,

    suggestions: [],
    textboxValues: {
      key: '',
      type: 1,
    },

    allStockCalValue: 0,
    allStockValue: 0,
  };

  columns = [
    {
      title: '序号',
      width: 300,
      render: (tags, record, index) => {
        return <span>{index + 1}</span>;
      },
    },

    {
      title: '股票',
      dataIndex: 'stock',
      key: 'stock',
      width: 300,
    },
    {
      title: '单数',
      dataIndex: 'billCount',
      key: 'billCount',
      width: 300,
      sorter: (a, b) => a.billCount - b.billCount,
    },
    {
      title: '敞口金额',
      dataIndex: 'stockValue',
      key: 'stockValue',
      width: 300,
      sorter: (a, b) => a.stockValue - b.stockValue,
    },
    {
      title: '敞口金额占比',
      dataIndex: 'stockValuePer',
      key: 'stockValuePer',
      width: 300,
      render: text => {
        let priceratetext = '';
        if (text > 0) {
          priceratetext = `${(text * 100).toFixed(2)}%`;
        }
        return <span>{priceratetext}</span>;
      },
      sorter: (a, b) => a.stockValuePer - b.stockValuePer,
    },
  ];

  // 默认加载数据-起始方法
  render() {
    const {
      fund: { RCNstockPerdata },
      loading,
      total,
    } = this.props;
    const {
      selectedRows,
      modalVisible,
      updateModalVisible,
      stepFormValues,
      listLoading,
    } = this.state;
    const newdata = {
      list: [],
      pagination: '',
    };
    if (RCNstockPerdata.code == 1) {
      newdata.list = RCNstockPerdata.list.billStockValuePerModels;
      newdata.pagination = RCNstockPerdata.pagination;
    }
    const { HistogramModalVisible } = this.state;
    const HistogramMethods = {
      handleHistogramVisible: this.handleHistogramVisible,
    };
    return (
      <PageHeaderWrapper title="RCN敞口">
        {/*        <div className={styles.controlBar}>
          <div
            style={{
              display: 'flex',
              flexFlow: 'row wrap',
              alignContent: 'space-between',
              alignItems: 'center',
            }}
          >
            <Button type="primary" className={styles.optionsbutton} onClick={() => this.upload(true)}>
              上传
            </Button>
            <input className="fileipt" type="file"/>
            <Button type="primary" className={styles.optionsbutton} onClick={() => this.search()}>
              查询
            </Button>
          </div>
        </div> */}
        <Card bordered={false}>
          <div className={styles.tableList}>
            <div className={styles.tableListForm}>{this.renderForm()}</div>
            <div className={styles.paginationMsg}>
              {'共'} {newdata.pagination.total} {'条数据'}
            </div>
            <br />
            {newdata.list.length == 0 ? (
              <Empty />
            ) : (
              <Table
                pagination={false}
                scroll={{ x: 1500, y: 800 }}
                columns={this.columns}
                dataSource={newdata.list}
                bordered
              />
            )}
          </div>
        </Card>
      </PageHeaderWrapper>
    );
  }

  // 加载完 之后 再加载 此 方法
  componentDidMount() {
    const { dispatch } = this.props;
    const { formValues } = this.state;
    dispatch({
      type: 'fund/GetRcnStockPer',
      payload: formValues,
      callback: response => {
        this.setState({
          dataTradeList: response.list.billStockValuePerModels,
          allStockCalValue: response.list.allStockCalValue,
          allStockValue: response.list.allStockValue,
        });
      },
    });
  }

  // 改变每页条数和当前页
  handleStandardTableChange = (pagination, filtersArg, sorter) => {
    const { dispatch } = this.props;
    const { formValues } = this.state;

    formValues.page = pagination.current;
    formValues.pagesize = pagination.pageSize;
    const params = {
      ...formValues,
    };
    dispatch({
      type: 'fund/GetFundTwoTradeList',
      payload: params,
    });
  };

  // 判断 菜单栏 是 缩放显示 还是 全部展示
  renderForm() {
    const { expandForm } = this.state;
    return expandForm ? this.renderAdvancedForm() : this.renderSimpleForm();
  }

  // 菜单栏- 点击展开显示 事件
  renderAdvancedForm() {
    const {
      form: { getFieldDecorator },
    } = this.props;
    return (
      <Form onSubmit={this.handleSearch} layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem label="最大财报日">
              {getFieldDecorator('maxEarningsDate ')(
                <DatePicker style={{ width: '100%' }} placeholder="请输入最大财报日" />
              )}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="最小财报日">
              {getFieldDecorator('minEarningsDate')(
                <DatePicker style={{ width: '100%' }} placeholder="请输入最小财报日" />
              )}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="最小保本幅度">
              {getFieldDecorator('minBreakEvenMargin')(<Input placeholder="请输入" />)}
            </FormItem>
          </Col>
        </Row>
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem label="最小权利金">
              {getFieldDecorator('minRoyalty')(<Input placeholder="请输入" />)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="最小收益率">
              {getFieldDecorator('minYieldRate')(<Input placeholder="请输入" />)}
            </FormItem>
          </Col>
        </Row>
        <div style={{ overflow: 'hidden' }}>
          <div style={{ marginBottom: 24 }}>
            <Button type="primary" htmlType="submit">
              查询
            </Button>
            <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>
              重置
            </Button>
            <a style={{ marginLeft: 8 }} onClick={this.toggleForm}>
              收起 <Icon type="up" />
            </a>
          </div>
        </div>
      </Form>
    );
  }

  // 菜单栏 默认收缩显示 事件
  renderSimpleForm() {
    const {
      form: { getFieldDecorator },
    } = this.props;
    return (
      <Form onSubmit={this.handleSearch} layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={5} sm={20}>
            <FormItem label="股票代码">
              {getFieldDecorator('stock')(<Input placeholder="请输入" />)}
            </FormItem>
          </Col>

          <Col md={5} sm={20}>
            <FormItem label="计算总敞口金额">
              {getFieldDecorator('allStockCalValue', {
                initialValue: this.state.allStockCalValue,
              })(<Input placeholder="请输入" disabled />)}
            </FormItem>
          </Col>

          <Col md={5} sm={20}>
            <FormItem label="实际总敞口金额">
              {getFieldDecorator('allStockValue', {
                initialValue: this.state.allStockValue,
              })(<Input placeholder="请输入" disabled />)}
            </FormItem>
          </Col>

          <Col md={5} sm={20}>
            <span className={styles.submitButtons}>
              <Button type="primary" htmlType="submit">
                查询
              </Button>
            </span>
          </Col>
        </Row>
      </Form>
    );
  }

  // 菜单栏-查询按钮 事件
  handleSearch = e => {
    e.preventDefault();
    const {
      dispatch,
      form,
      fund: { RCNstockPerdata },
    } = this.props;
    const { formValues, dataTradeList } = this.state;

    form.validateFields((err, fieldsValue) => {
      if (err) return;

      const values = {
        ...fieldsValue,
      };
      RCNstockPerdata.list = dataTradeList.filter(
        (item, index, arr) => item.stock.indexOf(values.stock.toUpperCase() || '') == 0
      );
      this.setState({
        updateParam: !this.state.updateParam,
      });
    });
  };

  // 菜单栏- 重置按钮 事件
  handleFormReset = () => {
    const { form, dispatch } = this.props;
    const { formValues } = this.state;
    form.resetFields();
    formValues.stock = '';
    dispatch({
      type: 'fund/GetBillGrade',
      payload: formValues,
      callback: () => {
        this.setState({
          listLoading: false,
        });
      },
    });
  };

  // 菜单栏- 展开 关闭 事件
  toggleForm = () => {
    const { expandForm } = this.state;
    this.setState({
      expandForm: !expandForm,
    });
  };

  upload = () => {
    window.open('/upload/V/DataCenter/RYData.aspx');
  };

  search = () => {
    const { dispatch } = this.props;
    const { formValues } = this.state;
    dispatch({
      type: 'fund/GetBillGrade',
      payload: formValues,
      callback: response => {},
    });
  };

  onSearch(value) {
    /*    const {
          rule: {filterData},
        } = this.props; */
    const { textboxValues, textLoading, suggestions } = this.state;
    this.state.textboxValues.key = value;
    const _this = this;
    // this.state.suggestions=[];
    if (value.length > 0) {
      this.props.dispatch({
        type: 'fund/GetTextBoxList',
        payload: textboxValues,
        callback: () => {
          const suggestionsData = [];
          for (let i = 0; i < _this.props.fund.filterData.list.length; i++) {
            suggestionsData.push(
              <Option key={_this.props.fund.filterData.list[i].address}>
                {_this.props.fund.filterData.list[i].value}
              </Option>
            );
          }
          _this.setState({
            suggestions: suggestionsData,
          });
        },
      });
    }
  }

  onSelect(value) {
    const { dispatch, form } = this.props;
    const { formValues, listLoading } = this.state;

    if (this.state.formValues.stock != undefined) {
      this.setState({
        listLoading: true,
      });
      dispatch({
        type: 'fund/GetBillGrade',
        payload: {
          stock: value,
        },
        callback: () => {
          this.setState({
            listLoading: false,
          });
        },
      });
    } else {
      message.warning('股票代码不能为空！');
    }
  }
}

export default RCNexposure;
